package com.picturetransform;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.picturetransform.R.id;
import com.picturetransform.binarization.PictureBinarization;

public class AndroidCameraControlActivity extends Activity {
    /** Called when the activity is first created. */
	
	private SurfaceView mView;
	private Camera mCamera;
	private Context mContext = this;
	private Button captureButton;
	private String TAG = "MEMORY";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);

        Log.i(TAG, " memoryInfo.availMem " + memoryInfo.availMem/(1024*1024) + "\n" );
        Log.i(TAG, " memoryInfo.lowMemory " + memoryInfo.lowMemory + "\n" );
        Log.i(TAG, " memoryInfo.threshold " + memoryInfo.threshold/(1024*1024) + "\n" );
        
        mCamera = getCameraInstance();
        mView = new CameraView(mContext,mCamera);
  
        ((FrameLayout)findViewById(R.id.view)).addView(mView);
        
        setButtonActive();
    }
    
    
    public void onStop(){
    	super.onStop();
    	   		mCamera.release();
    	   		finish();
    }
    
    AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){

    	  @Override
    	  public void onAutoFocus(boolean arg0, Camera arg1) {
    	   captureButton.setEnabled(true);
    	   mCamera.takePicture(null, mPictureCallback, mPictureCallback);
    	  }};
    
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        }
        catch (Exception e){
          
        }
        return c; 
    }
    
    public void setButtonActive(){
		captureButton = (Button) findViewById(id.takePicture);
	    captureButton.setOnClickListener(
	        new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	captureButton.setEnabled(false);
	            mCamera.autoFocus(myAutoFocusCallback);
	        }
	    }
	    );
	   }
    
	PictureCallback mPictureCallback = new PictureCallback() 
	{
		public void onPictureTaken(byte[] imageData, Camera c)
		{
			if (imageData != null)
			{
				StoreByteImage(mContext, imageData, 50, "ImageName");
			}
		}
	};
	
	public boolean StoreByteImage(Context mContext, byte[] imageData,
			int quality, String expName) {
		
		FileOutputStream binarizedImageFOS = null;
		FileOutputStream sourceImageFOS = null;
		
		ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
		activityManager.getMemoryInfo(memoryInfo);

		Log.i(TAG, " memoryInfo.availMem " + memoryInfo.availMem + "\n" );
		Log.i(TAG, " memoryInfo.lowMemory " + memoryInfo.lowMemory + "\n" );
		Log.i(TAG, " memoryInfo.threshold " + memoryInfo.threshold + "\n" );

		List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();


		
/*	Wczytanie z SD 2
		File root = Environment.getExternalStorageDirectory();
		 if (root.canWrite()){
		        File gpxfile = new File(root, filePath);
		    	FileInputStream input = null;
				try {
					input = new FileInputStream(gpxfile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				BufferedInputStream inputStream = new BufferedInputStream(input);
				try {
					inputStream.read(imageData);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
	//*/	
		
			BitmapFactory.Options options = new BitmapFactory.Options();
			
			int inSampleSize = 1;
			
			while(imageData.length/inSampleSize >= 786432) {
				inSampleSize++;
			}
			options.inSampleSize = inSampleSize;

			Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,imageData.length, options);
			Log.d("size width_height", ""+myImage.getWidth()+myImage.getHeight());
			
			Bitmap bmp = binConversion(myImage);
			
			displayAnImage(bmp);
			try {
				binarizedImageFOS = new FileOutputStream(String.format("/sdcard/bin_%d.png", System.currentTimeMillis()));

				BufferedOutputStream bos = new BufferedOutputStream(
						binarizedImageFOS);
				bmp.compress(CompressFormat.PNG, quality, bos);
				bos.flush();
				bos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				sourceImageFOS = new FileOutputStream(String.format("/sdcard/src_%d.png", System.currentTimeMillis()));

				BufferedOutputStream bos = new BufferedOutputStream(
						sourceImageFOS);
				myImage.compress(CompressFormat.PNG, quality, bos);
				bos.flush();
				bos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		
		return true;
	}
	
	public void displayAnImage(Bitmap mBmp){
		Bitmap mBitmap = mBmp;
		setContentView(new BitMapView(this,mBitmap));
		
	}
	
	public Bitmap binConversion(Bitmap bmp){
		return new PictureBinarization().adaptiveBinarization(bmp);
	}
	
}